import { getCurrentUserActionList, login } from '@/services/user/login';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { Alert } from 'antd';
import React, { useEffect } from 'react';
import { history } from 'umi';
import styles from './login.less';
// @ts-ignore
import { inArray, isNull, showMsg } from '@/utils/utils';

const LoginMessage: React.FC<{ content: string; }> = ({ content }) => (
  <Alert
    style={{ marginBottom: 24 }}
    message={content}
    type="error"
    showIcon
  />
);

const fetchUserActionList = async () => {
  try {
    const actionList = await getCurrentUserActionList();
    return actionList;
  } catch (error) {
    console.log(error);
  }
  return [];
};

/** 此方法会跳转到 redirect 参数所在的位置 */
const goto = async () => {
  if (!history) return;
  console.log('history', history)
  const { page, eventNo } = history.location.query as any;
  const actionList: any[] = await fetchUserActionList();
  const buttonIdList = actionList.map((item) => {
    return item.button_id;
  });
  localStorage.setItem('buttonIdList', JSON.stringify(buttonIdList));

  // 跳转到指定页面前先判断权限
  if (!isNull(page)) {
    switch (page) {
      case 'onetimeorder':
        if (inArray(buttonIdList, '400400001')) {
          location.href = `/order/one-time-order/doctor-bill?type=add&eventNo=${eventNo}`;
          // window.open(`${imgPrefix}/order/one-time-order/doctor-bill?type=add&eventNo=${eventNo}`);
        } else {
          location.href = '/welcome?nopermission=true'
          // window.open(`${imgPrefix}/welcome?nopermission=true`);
        }
        break;
      case 'planorder':
        if (inArray(buttonIdList, '400401001')) {
          location.href = `/order/planOrder/detail?type=add&eventNo=${eventNo}`;
          // window.open(`${imgPrefix}/order/planOrder/detail?type=add&eventNo=${eventNo}`);
        } else {
          location.href = '/welcome?nopermission=true'
          // window.open(`${imgPrefix}/welcome?nopermission=true`);
        }
        break;
      case 'discharged':
        if (inArray(buttonIdList, '400404000')) {
          location.href = `/order/discharged?eventNo=${eventNo}`;
          // window.open(`${imgPrefix}/order/discharged?eventNo=${eventNo}`);
        } else {
          location.href = '/welcome?nopermission=true'
          // window.open(`${imgPrefix}/welcome?nopermission=true`);
        }
        break;
      default:
        break;
    }
    return;
  }
  location.href = '/';
  // window.open(`${imgPrefix}/`);
};

const Login: React.FC = () => {
  useEffect(() => {
    const { query = {} } = history.location;
    if (query.tokenCode) {
      // Cookies.set('Oper-Token', query.tokenCode);
      localStorage.setItem('Oper-Token', query.tokenCode as string);
    } else {
      // Cookies.set('Oper-Token', '');
      localStorage.setItem('Oper-Token', '');
    }
    if (query.tokenCode) {
      login({ ...query }).then(() => {
        goto();
      }).catch(error => {
        showMsg(error?.data?.errmsg);
      });
    }
  }, []);

  return (
    <div className={styles.container} style={{ display: 'none' }}>
      <div className={styles.content}>
        <div className={styles.main}>
          <ProForm
            submitter={{
              searchConfig: {
                submitText: '登录'
              },
              render: (_, dom) => dom.pop(),
            }}
            onFinish={async (values) => {
            }}
          >
            {status === 'error' && (
              <LoginMessage
                content='账户或密码错误（admin/ant.design)'
              />
            )}

            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined className={styles.prefixIcon} />,
              }}
              placeholder='用户名: admin or user'
              rules={[
                {
                  required: true,
                  message: '请输入用户名!'
                }
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined className={styles.prefixIcon} />
              }}
              placeholder='密码: ant.design'
              rules={[
                {
                  required: true,
                  message: '请输入密码！'
                }
              ]}
            />
          </ProForm>
        </div>
      </div>
    </div>
  );
};

export default Login;
